<?php

class Ext_Model_UserRole extends Ext_Db_Table
{

    protected $_name = 'sys_user_role';

    protected $_sequence = false;

    protected $_primary = array( 'user_id', 'role_id' 
    );

    protected $_referenceMap = array( 
		'User' => array( 
        	'columns' => 'user_id', 
            'refTableClass' => 'Ext_Model_User', 
            'refColumns' => 'user_id' 
		), 
        'Role' => array( 
        	'columns' => 'role_id', 
			'refTableClass' => 'Ext_Model_Role', 
            'refColumns' => 'role_id' 
		) 
    );

    public function clearRoles( $userId )
    {
        $sql = $this->getAdapter()->quoteInto("USER_ID = ?", $userId);
        return $this->getAdapter()->delete( $this->_name, $sql  );
    }

    public function addRole( $userId, $roles )
    {
        if ( ! is_array( $roles ) ) {
            $roles = array( $roles );
        }
        
        $roleDb = new Ext_Model_Role( $this->getAdapter() );
        foreach ( $roles as $role ) {
            $roleId = $roleDb->getRoleId( $role );
            if ( empty( $roleId ) ) {
                throw new Exception( "role $role not found" );
            }
            $row = $this->find( $userId, $roleId )->current();
            if ( empty( $row ) ) {
                $this->insert( array( 
					"user_id" => $userId, 
                    "role_id" => $roleId 
                ) );
            }
        }
    
    }

}

